package 回显程序2_2线程;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpThreadEchoServer {
    //与回显程序2差不多，只不过引入了多线程
    //针对每个客户端都搞一个新线程
    private ServerSocket listenSocket=null;

    public TcpThreadEchoServer(int port) throws IOException {
        listenSocket=new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            Socket clientSocket=listenSocket.accept(); //主线程中始终调用 accept()，每次有一个新连接都交给一个线程来处理请求响应

            //创建一个线程来给客户端提供服务
            //保证 accept()调用完毕后，就能立刻再次调用 accept(),就是实现服务多个客户端
            Thread t=new Thread() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
    }



    //和回显程序2相同
    private void processConnection(Socket clientSocket) throws IOException {
        String log=String.format("[%s : %d] 客户端上线！！",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        System.out.println(log);

        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()) {

            while (true) {
                //1.读取请求并解析
                Scanner scanner=new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    //如果没有下一个，判断为 客户端下线
                    log=String.format("[%s : %d] 客户端下线！！！",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    System.out.println(log);
                    break;
                }
                String request=scanner.next();

                //2.根据请求计算响应
                String response=process(request);

                //3.将响应写回客户端
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();

                log=String.format("[%s : %d]  request:%s , response:%s",clientSocket.getInetAddress().toString(),clientSocket.getPort()
                                                                        ,request,response);
                System.out.println(log);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    //回显服务器，直接返回客户端的请求即可
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server=new TcpThreadEchoServer(9090);
        server.start();
    }
}
